var ajaxResponseObj;
var CAT = 0;
var DIAGRAMS = 0; //select Diagram option
var TotalsCache = {}; //object
var CategoriesCache = {};
var shortMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var COLORS = ['#4572A7', '#C33E31', '#86A24C', '#3D2614'];
var PlotLabels=[];

/**
 * Am object that contain info about checkboxes that must be hidden.
 */

var CustomGraphsHidden = {};
var REQUEST_DATA = {  
  datefrom: 0,
  dateto: 0,
  categoryId: 13,
  timeunit: 0
}

/**
 * Perform a new request to api/stats.php.
 */
function GetStats(categoryId)
{
  REQUEST_DATA.datefrom = document.getElementById('datefrom').value;
  REQUEST_DATA.dateto = document.getElementById('dateto').value;
  REQUEST_DATA.timeunit = document.getElementById('timeunit').value;
  REQUEST_DATA.categoryId = categoryId;
 
  var params = $.extend(REQUEST_DATA, {action: "get-categories"});

  $.ajax({
    type: "GET",
    url: "../../../admin/api/GetProductsData.php",
    data: params,
    success: GetCategoriesSuccess
  });


}
function GetCategoriesSuccess(obj)
{
  ajaxResponseObj = eval('(' + obj + ')');

  var html = "<select id = 'category_selector' onchange = 'CheckResponseStatus(); return false;'>";
 
  for (var key in ajaxResponseObj)
    {
      html += '<option'
      if(ajaxResponseObj[key]['ID']==REQUEST_DATA.categoryId)
        html += ' selected="selected"';
      
      html += ' value="'+ ajaxResponseObj[key]['ID'] +'">'+ ajaxResponseObj[key]['category_name'] +'</option>';
    }
    
  html += '</select>'
  +'<script type="text/javascript">'
            +'$("select").multiselect('
            +'{'
             +' multiple: false,'
             +' header: "Select an option",'
             +' noneSelectedText: "Select an Option",'
             +' selectedList: 1'
            +'});'

          +'</script>'
  
  $('#category_select_id').html(html);

  
  var params = $.extend(REQUEST_DATA, {action: "get-data"});
  $.ajax({
    type: "GET",
    url: "../../../admin/api/GetProductsData.php",
    data: params,
    success: GetStatsSuccess
  });
 
}

function GetStatsSuccess(response)
{
  ajaxResponseObj = eval('(' + response + ')');
  TotalsCache[REQUEST_DATA.datefrom + ', ' + REQUEST_DATA.dateto + ', ' + REQUEST_DATA.categoryId + ', ' + REQUEST_DATA.timeunit] = ajaxResponseObj;
  PopulateTableResults(ajaxResponseObj);
  var data = GetMostPopularCategories(ajaxResponseObj);
  PlotAccordingToChoices(data, GetFlotTicks(ajaxResponseObj));
  DrawFlot(data, GetFlotTicks(ajaxResponseObj));

}


function CheckResponseStatus()
{
  var datefrom = document.getElementById('datefrom').value;
  var dateto = document.getElementById('dateto').value;
  REQUEST_DATA.timeunit = document.getElementById('timeunit').value;
  var categoryID ;


  if(document.getElementById('category_selector'))
      categoryID = document.getElementById('category_selector').value;
  else
  categoryID = REQUEST_DATA.categoryId;

  if (typeof TotalsCache[REQUEST_DATA.datefrom + ', ' + REQUEST_DATA.dateto + ', ' + REQUEST_DATA.categoryID + ', ' + REQUEST_DATA.timeunit] != 'undefined')
  {
    if(TotalsCache[datefrom + ', ' + dateto + ', ' + categoryID + ', ' + REQUEST_DATA.timeunit] != null)
    {
      var data = GetMostPopularCategories(TotalsCache[datefrom + ', ' + dateto + ', ' + REQUEST_DATA.categoryId + ', ' + REQUEST_DATA.timeunit]);
      var Cache =  TotalsCache[datefrom + ', ' + dateto + ', ' + categoryID + ', ' + REQUEST_DATA.timeunit];

      DrawFlot(data, GetFlotTicks(Cache));
      PopulateTableResults(TotalsCache[datefrom + ', ' + dateto + ', ' + categoryID + ', ' + REQUEST_DATA.timeunit]);
    } 
    else GetStats(categoryID); 
  }

  else
  {
    GetStats(categoryID); 
  }

}

function GetMostPopularCategories(obj)
{
  var data = [];
  var i=0;
  var cat_num=4;
  
  for (var key in obj) 
  {
    var nr_par=0;
    if(i<cat_num)
    {
      var pointer = [];

      for (var keys in obj[key])
      {
        if(nr_par % GetDaysNumber(REQUEST_DATA.datefrom, REQUEST_DATA.dateto,REQUEST_DATA.timeunit) == 0)
        {
          var point = [];
          point[0] = obj[key][keys]['range-start'];
          point[1] = obj[key][keys]['value'];
          pointer.push(point);       
        }
        
        nr_par++;
        data[key] = pointer;
      }
      i++;
    }
  }
return data;
}

function DrawFlot(data, object)
{

  var options = {
    
      legend: { 
                show: true,
                labelFormatter: function (label) {
                    var cb = label;
                    return cb;}
              },
              
      xaxis: {
      monthNames: shortMonthNames,
      mode: 'time',
      timeformat: '%d %b'
      
    },
    yaxis: {
      min: 0, max: 5000
    }
  };
 
  var series = [];
  var i = 0;
  
  $("#choices").find("input:checked").each(function () {
    var key = $(this).attr("name");
    if (key && data[key])
    {
          data.push(data[key]);
          series.push({
          label : key,
          color: COLORS[i++],
          data: data[key],
          tooltip: {
            show: true,
            tooltipFormatter: function(item) 
            {
              return _tooltipFormatter(item,item.series.color)
            }
          } 
          });

    }
  });

    options.xaxis.ticks= object; 

  
  window.priceHistoryGraph = new FlotWrapper("product-price-history-flot", series, options);

  function _tooltipFormatter(item, color)
  {
    var labelData = item.series.xaxis.ticks[item.dataIndex].label;
    var views = item.datapoint[1];
    return '<span class="content popup-shadow" style="border-color: ' + color + '"> <b> '+ item.series.label +'</b>&#44; on ' + labelData + '<b style = "color: ' + color + ';"> ' + views + '</b>  views</span>';
  }
}





function OnClickCustomPlotChoise(event)
{
  var data = event.data.data;
  var timeunit = event.data.timeunit;

  var inputEl = event.currentTarget;
   
  CustomGraphsHidden[inputEl.name] = !inputEl.checked;
  DrawFlot(data, timeunit);

}



function BuildCustomChoicesHTML(data)
{
  var html = '';
  for (var key in data)
  {
    var categoryName = key;//category name
    var checked = true;
    if (typeof CustomGraphsHidden[key] != 'undefined' && CustomGraphsHidden[key])
      checked = false;

    html += '<input type="checkbox" name="' + categoryName +
      '" '+(checked? 'checked="checked"' : '')+' id="id-' + categoryName + '" />' +
      '<strong><label for="id-' + categoryName + '">' + categoryName + '</strong></label> &nbsp;';
  }
  return html;
}




function PlotAccordingToChoices(data, timeunit)
{ 
  var choiceContainer = $('#choices');
  $('#choices').html(BuildCustomChoicesHTML(data));
  $(choiceContainer).find("input").bind("click", 
                                      {data: data, timeunit: timeunit}, 
                                      OnClickCustomPlotChoise);
}






